package q48

import (
	"fmt"
	"log"
	"strings"
)

func rotate(matrix [][]int) {
	n := len(matrix)

	for i := 0; n > 1; i++ {
		n = n - 2
		rotateCircle(matrix, i)
	}
}

//旋转第n圈，从外到里，最外面一圈为1
func rotateCircle(matrix [][]int, index int) {
	l := len(matrix) - 2*index - 1
	//log.Printf("index:%d,len:%d", index, l)

	for i := 0; i < l; i++ {
		//log.Printf("use point: %d,%d", index, index+i)
		rotateOne(matrix, index, index+i)
	}
}

//对每个点进行旋转
// (i,j) => (j,n-1-i)
func rotateOne(matrix [][]int, x, y int) {
	n := len(matrix)
	//log.Printf("(%d,%d)", x, y)

	v := matrix[x][y]
	for i := 1; i <= 4; i++ {
		x, y = y, n-1-x
		v1 := matrix[x][y]
		matrix[x][y] = v
		v = v1
	}
}

func viewMatrix(matrix [][]int) {
	log.Printf(strings.Repeat("=", 20))
	n := len(matrix)
	for i := 0; i < n; i++ {
		for j := 0; j < n; j++ {
			fmt.Printf("%3d", matrix[i][j])
		}
		fmt.Println("")
	}
}
